package com.itcast.common.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import java.io.FileInputStream;
import java.io.*;

public class OSSUtils2 {
    private static String endpoint  = "oss-cn-shenzhen.aliyuncs.com";
    private static String accessKeyId  = "xxxxxx";
    private static String accessKeySecret  = "xxxxxx";
    private static String bucketName = "xxxxxx";
    private static String ossPath = "health/";
    private static OSS ossClient;

    /**
     *@Title:create
     *@Description 获取ossClient客户端
     */
    public static void create(){
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     *@Title:close
     *@Description 关闭ossClient客户端
     */
    public static void close(){
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

    /**
     *@Title:uploadByInputStream
     *@Description 本地路径上传
     *@param localpath 本地路径
     * @param fileName 文件名
     */
    public void uploadByLocaPath(String localpath,String fileName) throws FileNotFoundException {
        File fileInputStream = new File(localpath);
        ossClient.putObject(bucketName, ossPath + fileName,fileInputStream);
    }

    /**
     *@Title:uploadByInputStream
     *@Description 文件流上传
     *@Param ossPath OSS上的路径
     */
    public void uploadByfileInputStream(String fileName,FileInputStream fileInputStream) {
        ossClient.putObject(bucketName, ossPath + fileName,fileInputStream);
    }

    /**
     *@Title:download
     *@Description 流式下载
     *@Param filePath OSS上的路径
     */
    public InputStream download(String filePath){
        OSSObject ossObject = ossClient.getObject(bucketName, filePath);
        InputStream content = ossObject.getObjectContent();
        return content;
    }


    /**
     *@Title:download
     *@Description 文件下载
     *@Param filePath OSS上的路径
     *@Param localPath 本地的路径+文件名
     */
    public void downloadToFile(String pathName ,String localPath){
        ossClient.getObject(new GetObjectRequest(bucketName, pathName), new File(localPath));
    }


    /**
     * @Title: delete
     * @Description: 根据key删除oss服务器上的文件
     * @param filePath 文件路径+文件名
     */
    public void delete(String filePath){
        // 创建OSSClient实例。
        ossClient.deleteObject(bucketName, filePath);
    }
}
